<template>
  <div>
    <el-row justify="space-between" align="middle" style="margin-bottom: 15px;">
      <el-col :span="12">
        <el-button type="primary" size="small" @click="$router.push('/addPost')">
          <i class="el-icon-plus"></i> 添加帖子
        </el-button>
        <el-button
            type="danger"
            size="small"
            style="margin-left: 10px;"
            @click="batchDelete"
            :disabled="selectedPosts.length === 0"
        >
          <i class="el-icon-delete"></i> 批量删除
        </el-button>
      </el-col>

      <el-col :span="10">
        <el-input
            v-model="searchQuery"
            placeholder="搜索帖子..."
            clearable
            size="small"
            prefix-icon="el-icon-search"
            @clear="currentPage = 1"
            @input="currentPage = 1"
        />
      </el-col>
    </el-row>

    <el-row :gutter="10" style="margin-bottom: 15px;">
      <el-col :span="6">
        <el-select v-model="statusFilter" placeholder="所有状态" clearable size="small" @change="currentPage=1">
          <el-option label="所有状态" :value="''" />
          <el-option label="驳回" :value="'2'" />
          <el-option label="审核中" :value="'1'" />
          <el-option label="未审核" :value="'0'" />
        </el-select>
      </el-col>

      <el-col :span="6">
        <el-select v-model="categoryFilter" placeholder="所有分类" clearable size="small" @change="currentPage=1">
          <el-option label="所有分类" :value="''" />
          <el-option label="帖子" :value="'1'" />
          <el-option label="公告" :value="'0'" />
        </el-select>
      </el-col>
    </el-row>

    <el-table
        :data="paginatedPosts"
        border
        style="width: 100%;"
        @selection-change="handleSelectionChange"
        ref="postTable"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="标题" min-width="180" />
      <el-table-column prop="content" label="内容" min-width="250" />
      <el-table-column prop="author" label="作者" width="120" />
      <el-table-column
          prop="status"
          label="状态"
          width="100"
          :formatter="statusFormatter"
      />
      <el-table-column
          prop="category"
          label="分类"
          width="100"
          :formatter="categoryFormatter"
      />
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button
              size="small"
              type="warning"
              icon="el-icon-edit"
              @click="goUpdatePost(row.id)"
          >编辑</el-button>
          <el-button
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="deletePost(row.id)"
              style="margin-left: 8px"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 15px; text-align: right;">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredPosts.length"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { pList, deletePost as apiDeletePost } from '@/api/post';

export default {
  name: 'PostManagement',
  data() {
    return {
      posts: [],
      currentPage: 1,
      pageSize: 10,
      searchQuery: '',
      statusFilter: '',
      categoryFilter: '',
      selectedPosts: [],
    };
  },
  computed: {
    filteredPosts() {
      const query = this.searchQuery.toLowerCase();
      return this.posts.filter(post => {
        const matchesSearch =
            post.title.toLowerCase().includes(query) ||
            post.content.toLowerCase().includes(query) ||
            post.author.toLowerCase().includes(query);
        const matchesStatus =
            this.statusFilter === '' || post.status.toString() === this.statusFilter;
        const matchesCategory =
            this.categoryFilter === '' || post.category.toString() === this.categoryFilter;
        return matchesSearch && matchesStatus && matchesCategory;
      });
    },
    paginatedPosts() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.filteredPosts.slice(start, start + this.pageSize);
    },
  },
  methods: {
    statusFormatter(row, column, cellValue) {
      // 根据你的状态定义：
      // 0 = 未审核，1 = 审核中，2 = 驳回
      switch (cellValue) {
        case 0:
          return '未审核';
        case 1:
          return '审核中';
        case 2:
          return '驳回';
        default:
          return '未知状态';
      }
    },
    categoryFormatter(row, column, cellValue) {
      const val = Number(cellValue);
      switch (val) {
        case 0:
          return '公告';
        case 1:
          return '帖子';
        default:
          return '未知分类';
      }
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
    },
    handleSelectionChange(selection) {
      this.selectedPosts = selection.map(item => item.id);
    },
    goUpdatePost(postId) {
      this.$router.push({ path: '/updatePost', query: { id: postId } });
    },
    batchDelete() {
      if (this.selectedPosts.length === 0) {
        this.$message.warning('请至少选择一个帖子');
        return;
      }
      this.$confirm('是否删除选中的帖子？', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            const deletePromises = this.selectedPosts.map(id => apiDeletePost(id));
            Promise.all(deletePromises)
                .then(results => {
                  const successCount = results.filter(res => res.code === 0).length;
                  if (successCount > 0) {
                    this.$message.success(`成功删除 ${successCount} 个帖子`);
                    this.fetchPosts();
                  } else {
                    this.$message.error('删除失败');
                  }
                })
                .catch(error => {
                  console.error('Error:', error);
                  this.$message.error('删除操作出错');
                });
          })
          .catch(() => {});
    },
    deletePost(postId) {
      this.$confirm('是否删除？', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            apiDeletePost(postId)
                .then(res => {
                  if (res.code === 0) {
                    this.$message.success('删除成功');
                    this.fetchPosts();
                  } else {
                    this.$message.error('删除失败: ' + (res.msg || '未知错误'));
                  }
                })
                .catch(error => {
                  console.error('Error:', error);
                  this.$message.error('网络请求出错');
                });
          })
          .catch(() => {});
    },
    fetchPosts() {
      pList()
          .then(res => {
            if (res.code === 0 && Array.isArray(res.data)) {
              this.posts = res.data;
              this.currentPage = 1;
            } else {
              this.$message.error('获取帖子列表失败');
            }
          })
          .catch(error => {
            this.$message.error('获取帖子列表失败');
          });
    },
  },

  mounted() {
    this.fetchPosts();
  },
};
</script>

<style scoped>
.el-table th,
.el-table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}
</style>
